<template>
  <div>
    <div>当前在线用户</div>
    <div @click="drawer = true">
      <el-avatar
        src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png"></el-avatar>
      <div>张三</div>
    </div>
    <el-drawer
      title="聊天界面"
      :visible.sync="drawer"
      :direction="direction"
      :before-close="handleClose"
      size="40%"
    >
      <websocket :ws = "ws" :to="to"></websocket>
    </el-drawer>
  </div>
</template>
<script>
import websocket from '@/views/chat/websocket'
import {onlineUser,onlineUserNum} from "@/api/chat/chatuser";

export default {
  components: {
    websocket
  },
  data() {
    return {
      url: "ws://127.0.0.1:8080/websocket/message",
      ws:null,
      drawer: false,
      direction: 'rtl',
      to:"2" // 要发送给谁
    };
  },
  methods: {
      handleClose(done) {
        this.$confirm('确认关闭？')
          .then(_ => {
            done();
          })
          .catch(_ => {});
      },
      join() {
      // 创建websocket连接 加入当前登录用户userId
      const wsuri = this.url + '/' + this.$store.state.user.id;
      this.ws = new WebSocket(wsuri);
      const self = this;
      this.ws.onopen =  (event) => {
        this.$message.success("连接成功"+event)
      };

      this.ws.onclose = (event) => {
        this.$message.error("已经关闭连接"+event)
      };
    },
  },
  mounted () {
    this.join();
    if(this.$store.state.user.id == "1"){
      console.log("我是1号用户");
      this.to = "2";
    }else{
      console.log("我是2号用户");
      this.to = "1";
    }

    this.ws.addEventListener('message', (event) => {
      let data = JSON.parse(event.data);
      if(data.to == '-1'){
        // 获取当前在线人数及人员
        onlineUserNum().then(res => {
          console.log(res);
        })
        onlineUser().then(res => {
          console.log(res);
        })

        this.$notify({
          title: '有新用户上线了',
          message: data.msg,
          type: 'warning'
        });
      }
    })


  }
};
</script>

<style scoped>
h1,
h2 {
  font-weight: normal;
}
</style>
